package ink.carnation.imtalk.aspect;

import ink.carnation.imtalk.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @Author 桂乙侨
 * @Date 2020/9/26 23:26
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class IMLogAspect {

    @Around("execution(* ink.carnation.imtalk.controller.*.*.*(..))")
    public Object logController(ProceedingJoinPoint point) {
        StringBuilder builder = new StringBuilder();
        builder.append(LocalDateTime.now());
        long start = System.currentTimeMillis();

        builder.append(" 开始执行 ");

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String method = request.getMethod();
        String url = request.getRequestURL().toString();
        String ip = IPUtils.getIpAddress(request);
        Object object = null;
        builder.append("请求地址：" + url + "  请求方法 " + method + " 请求 IP：" + ip);
        try {
            object = point.proceed();

        } catch (Throwable throwable) {
            builder.append("执行出错");
        }finally {
            long end = System.currentTimeMillis();
            builder.append(" 执行结束，共执行：" + (end - start)+"ms");
            log.info(builder.toString());
            return object;
        }
    }
}
